# -*- coding:utf-8 -*-
"""
Create by Jim on2019/01/09
"""
from flask import jsonify, request, g, current_app

from info.models import Area, User
from info.utils.authentication import real_authentication
from info.utils.resp_model import RespViewModel
from info.utils.response_code import RET, error_map
from info.utils.common import login_required

from . import usr

@usr.route('/usr/', methods=['GET'])
@login_required
def usr():
    if request.method == 'GET':
        data = {
            "avatar_url": request.remote_addr,
            "mobile": g.user.mobile,
            "name": g.user.name
        }
        jsonify(RespViewModel(RET.OK, error_map.get(RET.OK), data).resp_data())
    return jsonify(RespViewModel())


@usr.route('/usr/name/', methods=['POST'])
@login_required
def user_name():
    if g.user.name != request.json.get('name', None):
        return jsonify(RespViewModel(RET.PARAMERR, error_map.get(RET.PARAMERR)).resp_data())
    return jsonify(RespViewModel(RET.OK, error_map.get(RET.OK)).resp_data())


@usr.route('/usr/avatar/', methods=['POST'])
@login_required
def user_avatar():
    avatar = request.files.get('avatar', None)
    if not avatar:
        return jsonify(RespViewModel(RET.NODATA, error_map.get(RET.NODATA)))
    g.user.avatar_url = avatar
    return jsonify(RespViewModel(RET.OK, error_map.get(RET.OK), {"avatar_url": g.user.avatar_url}))


@usr.route('/usr/auth/', methods=['GET', 'POST'])
@login_required
def imagecode():
    if request.method == 'GET':
        data = {
            "real_name": g.user.name,
            "id_card": g.user.id_card
        }
        return jsonify(RespViewModel(RET.OK, error_map.get(RET.OK), data))
    name = request.json.get("real_name", None)
    card = request.json.get("id_card", None)
    if not all([name, card]):
        return jsonify(RespViewModel(RET.NODATA), error_map.get(RET.NODATA))
    if not real_authentication(name, card):
        return jsonify(RespViewModel(RET.DATAERR, error_map.get(RET.DATAERR)))
    return jsonify(RespViewModel(RET.OK, error_map.get(RET.OK)))

@usr.route('/usr/house', methods=['GET'])
@login_required
def user_houses():
    data=[]
    for house in g.user.houses:
        data.append(house.house_dict)
    return jsonify(RespViewModel(RET.OK,error_map.get(RET.OK),data))


@usr.route('/usr/areas', methods=['GET'])
def user_areas():
    try:
        areas=Area.query.all()
    except Exception as e:
        current_app.logger.debug("数据库查询错误")
        return jsonify(RespViewModel(RET.DBERR,error_map.get(RET.DBERR)))
    data=[]
    for i in areas:
        data.append(i.to_dict)
    return jsonify(RespViewModel(RET.OK,error_map.get(RET.OK),data))
